package com.sz.mes.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.entity.PurchaseOrder;
import com.sz.mes.entity.RequestPurchase;
import com.sz.mes.entity.TableHead;
import com.sz.mes.mapper.RequestPurchaseMapper;
import com.sz.mes.mapper.TableHeadMapper;
import com.sz.mes.service.RequestPurchaseService;
import com.sz.mes.service.impl.BaseCustomServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 请购订单相关Service实现
 *
 * @author hem
 * @version 1.0
 * @date 2023-11-09
 * Copyright © szhs
 */
@Service
@Slf4j
public class RequestPurchaseServiceImpl extends BaseCustomServiceImpl<RequestPurchaseMapper, RequestPurchase> implements RequestPurchaseService {

    private RequestPurchaseMapper requestPurchaseMapper;
    private TableHeadMapper tableHeadMapper;

    public RequestPurchaseServiceImpl(RequestPurchaseMapper requestPurchaseMapper, TableHeadMapper tableHeadMapper) {
        this.requestPurchaseMapper = requestPurchaseMapper;
        this.tableHeadMapper = tableHeadMapper;
    }

    @Override
    public JsonResult insert(RequestPurchase entity) {
        RequestPurchase requestPurchase = new RequestPurchase();
        requestPurchase.setExcelData(entity.getExcelData());
        try {
//            productTaskMapper.insert(productTask);
            if (requestPurchase.getExcelData() != null) {
                return dataProcess(requestPurchase.getExcelData(), requestPurchase.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JsonResult.OK("导入数据成功");
    }


    private JsonResult dataProcess(String excelData, Long requestPurchaseId) throws ParseException {
        //mapList 获取到所有的数据
        ArrayList<Map<String, String>> mapList = new ArrayList<>();


        //hashMap 表头对应的 序号
        HashMap<String, String> hashMap = new HashMap<>();
        //获取表头
        TableHead tableHead = tableHeadMapper.selectById(6);

        String data = tableHead.getData();
//        String replaceAll = data.replaceAll("\\\\", "");
//        System.out.println(data);
//        System.out.println(replaceAll);

        JSONObject jsonObject = JSONObject.parseObject(tableHead.getData());
        for (Object map : jsonObject.entrySet()) {
//            hashMap.put(String.valueOf(((Map.Entry)map).getValue()),String.valueOf(((Map.Entry)map).getKey()));
            hashMap.put(String.valueOf(((Map.Entry) map).getKey()), String.valueOf(((Map.Entry) map).getValue()));
        }

        //获取完表头信息后清楚数据，给其他数据用
        mapList.clear();

        System.out.println("excelData:" + excelData);

        //json转为List
        JSONArray objects = JSONObject.parseArray(excelData);
//        JSONArray objects = JSONObject.parseArray(JSONObject.toJSONString(excelData));
        for (Object object : objects) {
            HashMap<String, String> map1 = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            mapList.add(map1);
        }

        System.out.println("mapList:" + mapList);

        for (Map map : mapList) {
            System.out.println(map);
            //请购订单
            RequestPurchase requestPurchase = new RequestPurchase();
            requestPurchase.setReceiptNum((String) map.get(hashMap.get("单据编号")));
            requestPurchase.setReceiptNumRow((String) map.get(hashMap.get("行号")));
            requestPurchase.setStatus(((String) map.get(hashMap.get("请购单状态"))));
            requestPurchase.setRemark(((String) map.get(hashMap.get("备注"))));
            requestPurchase.setPlanNum(((String) map.get(hashMap.get("计划号"))));
            requestPurchase.setProductNum((String) map.get(hashMap.get("料品.料号")));
            requestPurchase.setProductName((String) map.get(hashMap.get("料品名称")));
            requestPurchase.setSpecification((String) map.get(hashMap.get("料品规格")));
            requestPurchase.setProductNameTwo((String) map.get(hashMap.get("品名2")));
            requestPurchase.setUnit((String) map.get(hashMap.get("采购单位")));
            requestPurchase.setRowStatus((String) map.get(hashMap.get("行状态")));
            requestPurchase.setCreateBy((String) map.get(hashMap.get("创建人")));
            requestPurchase.setAuditor((String) map.get(hashMap.get("审核人")));
            requestPurchase.setPurchaseRemark((String) map.get(hashMap.get("请购单行集合.备注")));
            requestPurchase.setRequestPersonName((String) map.get(hashMap.get("需求人员.名称")));

           /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!" ".equals(map.get(hashMap.get("业务日期"))) && !" ".equals(map.get(hashMap.get("要求交货日期")))
                    &&!" ".equals(map.get(hashMap.get("审核日期")))) {
                String deliveryTime = (String) (map.get(hashMap.get("业务日期")));
                String businessTime = (String) (map.get(hashMap.get("要求交货日期")));
                String auditTime = (String) (map.get(hashMap.get("审核日期")));
                Date deliveryDate = sdf.parse(deliveryTime);
                Date businessDate = sdf.parse(businessTime);
                Date auditDate = sdf.parse(auditTime);
                requestPurchase.setDeliveryDate(deliveryDate);
                requestPurchase.setBusinessDate(businessDate);
                requestPurchase.setAuditDate(auditDate);
            }*/
            requestPurchase.setBusinessDate((String) map.get(hashMap.get("业务日期")));
            requestPurchase.setDeliveryDate((String) map.get(hashMap.get("要求交货日期")));
            requestPurchase.setAuditDate((String) map.get(hashMap.get("审核日期")));

            Integer purchaseQuantity = (Integer) map.get(hashMap.get("核准采购数量"));
            if (purchaseQuantity != 0) {
                requestPurchase.setPurchaseQuantity(purchaseQuantity);
            } else {
                requestPurchase.setPurchaseQuantity(0);
//                productTask.setQuantity(0);
            }

            Integer transferPONum = (Integer) map.get(hashMap.get("累计转PO数量"));
            if (transferPONum != 0) {
                requestPurchase.setTransferPoNum(transferPONum);
            } else {
                requestPurchase.setTransferPoNum(0);
            }

            Integer actualQuantity = (Integer) map.get(hashMap.get("累计实到数量"));
            if (actualQuantity != 0) {
                requestPurchase.setActualQuantity(actualQuantity);
            } else {
                requestPurchase.setActualQuantity(0);
            }

            try {
                requestPurchaseMapper.insert(requestPurchase);
            } catch (Exception e) {
                return JsonResult.FAIL_OPERATION("插入失败" + e.getMessage());
            }
            //任务单处理结束
        }

        return JsonResult.OK("数据导入成功");

    }


    @Override
    public List<String> filterDuplicate(List<String> receiptNumAndRowList) {
        if (V.isEmpty(receiptNumAndRowList)) {
            return Collections.emptyList();
        }

        List<String> trimDuplicateData = new ArrayList<>();
        List<String> duplicateData = requestPurchaseMapper.selectDuplicateData(receiptNumAndRowList);
        for (String duplicateDatum : duplicateData) {
            String trim = duplicateDatum.trim();
            trimDuplicateData.add(trim);
        }
//        LambdaQueryWrapper<ProductTask> wrapper = new LambdaQueryWrapper<>();
//        wrapper.in(ProductTask::getSplice, receiptNumAndStockNumList);
//        List<String> receiptNumAndStockNumLists = getValuesOfField(productTaskQueryWrapper, ProductTask::getSplice);


        return trimDuplicateData;
    }
}
